package chapter01.part1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 从集合转换到流的操作
 * 
 * @author insight 
 * @since 2021/7/19
 */
public class CountWordByLength {
    public static void main(String[] args) {
        // create word list
        List<String> wordList = getWordList();
        int bound = 10;

        // 1 loop & cnt
        AtomicLong loopCnt = new AtomicLong();
        wordList.forEach(w -> {
            if (w.length() > bound) {
                loopCnt.incrementAndGet();
            }
        });
        System.out.println(loopCnt);

        // 2 stream
        long streamCount = wordList.stream().filter(w -> w.length() > bound).count();
        System.out.println(streamCount);

        // 3 parallelStream
        long parallelStreamCnt =
                wordList.parallelStream().filter(w -> w.length() > bound).count();
        System.out.println(parallelStreamCnt);
    }

    public static List<String> getWordList() {
        int cnts = 1000;
        ArrayList<String> words = new ArrayList<>(cnts);

        for (int i = 0; i < cnts; i++) {
            int wordLength = ThreadLocalRandom.current().nextInt(2, 15);
            StringBuilder word = new StringBuilder();

            for (int j = 0; j < wordLength; j++) {
                word.append(getCase());
            }

            words.add(word.toString());
        }

        return words;
    }

    private static char getCase() {
        return (char) ('a' + ThreadLocalRandom.current().nextInt(26));
    }
}